<template>
    <div>
        <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 年级列表卡片区 -->
        <el-card class="box-card">
            <el-form :inline="true" ref="form" :model="queryMap" label-width="70px" size="small">
              <el-form-item label="学员姓名">
                <!--  <el-select v-model="queryMap.studentid" placeholder="请选择学员">
                      <el-option
                              v-for="student in studentList"
                              :key="student.studentId"
                              :label="student.studentName"
                              :value="student.studentId"
                      ></el-option>
                  </el-select>-->
                <el-autocomplete
                    value-key="name"
                    :clearable="true"
                    class="inline-input"
                    v-model="queryMap.studentName"
                    :fetch-suggestions="querySearch"
                    placeholder="搜索学生名字"
                    @select="handleSelect" style="width: 288px"
                ></el-autocomplete>
              </el-form-item>

              <el-form-item label="考试时间">
                <el-date-picker
                    :clearable="false"
                    v-model="range"
                    type="datetimerange"
                    :value-format="'yyyy-MM-dd HH:mm:ss'"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="考试项目">
                <el-select
                    clearable
                    @change="searchStudentScore"
                    @clear="searchStudentScore"
                    v-model="queryMap.examTypeId"
                    placeholder="请选择考试项目"
                >
                  <el-option
                      v-for="examType in examTypes"
                      :label="examType.examTypeName"
                      :key="examType.examTypeId"
                      :value="examType.examTypeId"
                  >
                    <span style="float: left">{{ examType.examTypeName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>

				
                <el-form-item style="margin-left:50px;">
                    <el-button  @click="reset" icon="el-icon-refresh">重置</el-button>
                    <el-button type="primary" @click="searchStudentScore" icon="el-icon-search">查询</el-button>
                </el-form-item>
            </el-form>
            <div style="margin-bottom: 10px;">
                <el-button
                        type="success"
                        icon="el-icon-plus"
                        @click="addDialogVisible=true"
                        v-hasPermission="'studentscore:add'"
                >添加</el-button>
                <el-button @click="downExcel" v-hasPermission="'studentscore:export'"  icon="el-icon-download">导出</el-button>
            </div>

            <!-- 表格区域 -->
            <el-table v-loading="loading" size="small" :data="studentScoreList" border style="width: 100%;" height="420" :cell-style="rowStyle">
                <!-- <el-table-column type="selection" width="40"></el-table-column> -->
                <el-table-column label="#" prop="scoreId" width="50"></el-table-column>
                <el-table-column prop="studentName" label="学生名称" width="110"></el-table-column>
               <el-table-column prop="examTypeName" label="考试项目" width="150"></el-table-column>
              <el-table-column prop="examTime" label="考试时间" width="120"></el-table-column>
              <el-table-column prop="examScore" label="考试成绩" width="120"></el-table-column>
                <el-table-column label="备注" width="220">
                    <template slot-scope="scope">
                        <!-- 光标放在文字上面 悬出内容区域 -->
                        <el-popover trigger="hover" placement="top">
                            <p>备注: {{ scope.row.remarks }}</p>
                            <div slot="reference" class="name-wrapper">
                                <el-tag size="medium">{{ scope.row.remarks }}</el-tag>
                            </div>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="操作" >
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" icon="el-icon-edit-outline" @click="edit(scope.row)"></el-button>
                        <el-button type="danger" size="small" icon="el-icon-delete" @click="del(scope.row.scoreId)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                    style="margin-top:10px;"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryMap.pageNo"
                    :page-sizes="[6, 10, 20, 30]"
                    :page-size="queryMap.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
            ></el-pagination>


            <!-- 添加对话框 -->
            <el-dialog :title="title" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
                <!-- 表单 -->
                <span>
          <el-form
                  :model="addForm"
                  :label-position="labelPosition"
                  :rules="addFormRules"
                  ref="addFormRef"
                  label-width="80px"
          >

                 <el-form-item label="学生姓名" prop="studentName" required>
                        <el-autocomplete
                            value-key="name"
                            :clearable="true"
                            class="inline-input"
                            v-model="addForm.studentName"
                            :fetch-suggestions="querySearch"
                            placeholder="搜索学生名字"
                            @select="handleSelect" style="width: 288px"
                        ></el-autocomplete>
                    </el-form-item>


                  <el-form-item label="考试项目" prop="examTypeId">
                    <el-select v-model="addForm.examTypeId" placeholder="请选择考试项目">
                      <el-option
                          v-for="examType in examTypes"
                          :key="examType.examTypeId"
                          :label="examType.examTypeName"
                          :value="examType.examTypeId"
                      ></el-option>
                    </el-select>
                  </el-form-item>


                <el-form-item prop="examTime" label="考试时间">
                    <el-col :span="12">
                      <el-date-picker
                          type="date"
                          value-format="yyyy年MM月dd日"
                          placeholder="选择考试日期"
                          v-model="addForm.examTime"
                          style="width: 185px;"
                      ></el-date-picker>
                    </el-col>
                  </el-form-item>

					
					<el-form-item label="考试成绩" prop="examScore">
                    <el-input v-model="addForm.examScore"></el-input>
                  </el-form-item>
                  
            <el-row>
                <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="addForm.remarks"></el-input>
            </el-form-item>
            </el-row>

          </el-form>
        </span>

                <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
                  type="primary"
                  @click="addStudentScore"
                  :loading="btnLoading"
                  :disabled="btnDisabled"
          >确 定</el-button>
        </span>
            </el-dialog>

        </el-card>
    </div>
</template>
<script>
    import axios from "axios";
    export default {
        data() {
          let validatorScore = (rule, value, callback) => {
            if (!value) return callback(new Error('请输入分数'))
            if (!Number(value)) return callback(new Error('请输入数字值'));
            callback();
          };
          var validatorName = (rule, value, callback) => {
            if (value) {
              if (!value) {
                callback(new Error("请输入学生姓名！"));
              } else {
                callback();
              }
            } else {
              callback(new Error("请输入学生姓名！"));
            }
          };
           return {
                title:'添加学生成绩',
             pickerOptions: {
               shortcuts: [
                 {
                   text: '今天(此刻)',
                   onClick(picker) {
                     const end = new Date();
                     const start = new Date(new Date(new Date().toLocaleDateString()).getTime());
                     picker.$emit('pick', [start, end]);
                   }
                 },
                 {
                   text: '昨天',
                   onClick(picker) {
                     const end = new Date(new Date(new Date().toLocaleDateString()).getTime());
                     const start = new Date(new Date(new Date().toLocaleDateString()).getTime());
                     start.setTime(start.getTime() - 3600 * 1000 * 24);
                     picker.$emit('pick', [start, end]);
                   }
                 },
                 {
                   text: '最近一周',
                   onClick(picker) {
                     const end = new Date();
                     const start = new Date();
                     start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                     picker.$emit('pick', [start, end]);
                   }
                 }, {
                   text: '最近一个月',
                   onClick(picker) {
                     const end = new Date();
                     const start = new Date();
                     start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                     picker.$emit('pick', [start, end]);
                   }
                 }, {
                 }, {
                   text: '最近两个月',
                   onClick(picker) {
                     const end = new Date();
                     const start = new Date();
                     start.setTime(start.getTime() - 3600 * 1000 * 24 * 60);
                     picker.$emit('pick', [start, end]);
                   }
                 }, {
                   text: '最近三个月',
                   onClick(picker) {
                     const end = new Date();
                     const start = new Date();
                     start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                     picker.$emit('pick', [start, end]);
                   }
                 }]
             },
                btnLoading: false,
                btnDisabled: false,
                examTypes: [],
                range:[],
                loading: true,
                total: 0,
                addDialogVisible: false, //添加对话框,
                editDialogVisible: false, //修改对话框
                assignDialogVisible: false, //分配角色对话框
                labelPosition: "right", //lable对齐方式
                //查询对象
                queryMap: {
                    pageNum: 1,
                    pageSize: 6,
                    examTime: "",
                    studentId:"",
                    examTypeId:"",
                    studentName:""
                },
               studentScoreList: [],
               getname:'',
               addForm:{
                   studentId:'',
                   examTypeId:'',
                   examTime:'',
                   examScore:'',
                   remarks:'',
               },
               addFormRules: {
                 studentName: [
                   { required: true, validator: validatorName, trigger: "change"},
                 ],
                 examScore:[
                   {required: true, validator: validatorScore, trigger: "blur"}
                 ],
                 examTime: [
                   { type: 'string', required: true, message: '请选择日期', trigger: 'change' }
                 ]
               }
            };
        },
        methods: {
            /**
             * 重置
             */
            reset(){
                this.queryMap= {
                  pageNum: 1,
                  pageSize: 6,
                  examTime: "",
                  studentName:"",
                  examTypeId:""
                };
            },
          //内容居中
          rowStyle() {
            return "text-align:center";
          },
          querySearch(queryString, cb) {
            if(queryString!='') {//输入框中有值
              this.findStuList(queryString, (data) => {
                console.log(data);
                var results = queryString ? data.filter(this.createStateFilter(queryString)) : data;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                  cb(results);
                }, 5000*Math.random());
              })
            }
          },
          findStuList(query,fun){
            if(query!='' && query !=null && query!= undefined){
              let params = {
                studentName:query
              }
              this.$http.post('/class/findStuList',params).then((res) =>{
                this.queryStudList = res.data
                this.shcoolClass = []
                if(this.queryStudList.length>0){
                  this.queryStudList.forEach((item)=>{
                    this.shcoolClass.push({
                      value:item.studentId,
                      name:item.studentName
                    })
                  })
                }else{
                  this.shcoolClass.push({
                    value:"未找到相关结果",
                    name:"未找到相关结果",
                  })
                }
                fun(this.shcoolClass);
              })
            }

          },
            /**
             * 加载年级表格
             */
            downExcel() {
                const $this = this;
                const res = axios
                    .request({
                        url: "http://localhost:8989/mark/excel",
                        method: "post",
                        responseType: "blob",
                        headers:{'Authorization':LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)},	//设置请求头
                    })
                    .then(res => {
                        if (res.headers["content-type"] === "application/json") {
                            return $this.$message.error(
                                "Subject does not have permission [class:export]"
                            );
                        }
                        const data = res.data;
                        let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
                        const a = document.createElement("a");
                        document.body.appendChild(a);
                        a.href = url;
                        a.download = "年级列表.xls";
                        a.click();
                        window.URL.revokeObjectURL(url);
                    });
            },


            /**
             * 加载学生成绩列表
             */
            async getStudentScoreList() {

              if(this.range!=null&&this.range.length===1){
                this.queryMap.startTime=this.range[0];
              }else if(this.range!=null&&this.range.length===2){
                this.queryMap.startTime=this.range[0];
                this.queryMap.endTime=this.range[1];
              }
              console.log("aaaaaa",this.queryMap);
                const { data: res } = await this.$http.get("/mark/findList", {
                    params: this.queryMap

                });
                if(!res.success){
                    return this.$message.error("获取学生成绩列表失败:"+res.data.errorMsg);
                }
                this.total = res.data.total;
                this.studentScoreList = res.data.rows;
                this.loading = false;
            },

            /**
             * 删除年级
             */
            async del(scoreId) {
                const res = await this.$confirm(
                    "此操作将永久删除该学生成绩, 是否继续?",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }
                ).catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
                if (res === "confirm") {
                    const { data: res } = await this.$http.delete("/mark/delete/" + scoreId);
                    console.log(res);
                    if(res.success){
                        this.$notify.success({
                            title:'操作成功',
                            message:'学生成绩删除成功',
                        });
                        await this.getStudentScoreList();
                    }else {
                        this.$message.error(res.data.errorMsg);
                    }
                }
            },
            /**
             * 添加成绩
             */
            async addStudentScore() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        return;
                    } else {
                        if(this.addForm.scoreId){
                            this.updateStudentScore()
                        }else{
                            this.saveStudentScore()
                        }
                    }
                });
            },
            async saveStudentScore(){
                this.btnLoading = true;
                this.btnDisabled = true;
                const { data: res } = await this.$http.post("/mark/add", this.addForm);
                if(res.success){
                    this.$notify.success({
                        title:'操作成功',
                        message:'成绩添加成功',
                    });
                    this.addForm = {};
                    await this.getStudentScoreList();
                } else {
                    return this.$message.error("成绩添加失败:" + res.data.errorMsg);
                }
                this.addDialogVisible = false;
                this.btnLoading = false;
                this.btnDisabled = false;
            },
            /**
             * 更新年级
             */
            async updateStudentScore() {
                this.btnLoading = true;
                this.btnDisabled = true;
                const { data: res } = await this.$http.put(
                    "/mark/update/" + this.addForm.scoreId,
                    this.addForm
                );
                if(res.success){
                    this.$notify({
                        title: "操作成功",
                        message: "成绩基本信息已更新",
                        type: "success"
                    });
                    this.addForm = {};
                    await this.getStudentScoreList();
                } else {
                    this.$message.error("成绩信息更新失败:" + res.data.errorMsg);
                }
                this.addDialogVisible = false;
                this.btnLoading = false;
                this.btnDisabled = false;
            },
            /**
             * 搜索年级
             */
            searchStudentScore() {
                this.queryMap.pageNum = 1;
                this.getStudentScoreList();
            },
            /**
             * 修改年级信息
             */
            async edit(row) {
                this.title ="编辑学生成绩信息";
                const { data: res } = await this.$http.get("/mark/edit/" + row.scoreId);
                if(res.success){
                    this.addForm = res.data;
                    this.addForm.studentId = row.studentId

                    this.addForm.studentName = row.studentName

                    this.addDialogVisible = true;
                } else {
                    return this.$message.error("学生成绩信息编辑失败:" + res.data.errorMsg);
                }
            },

          clearTime(){
            this.queryMap= {pageNum: 1, pageSize: 6,studentId:'',examTypeId:''};
            this.queryMap.startTime=null;
            this.queryMap.endTime=null;
            this.range=[];
          },


            /**
             *  改变页码
             */
            handleSizeChange(newSize) {
                this.queryMap.pageSize = newSize;
                this.getStudentScoreList();
            },
            /**
             * 翻页
             */
            handleCurrentChange(current) {
                this.queryMap.pageNum = current;
                this.getStudentScoreList();
            },

          /**
           * 加载所有考试项目
           */
          async getExamType() {
            const { data: res } = await this.$http.get("project/findAll");
            if(!res.success){
              return this.$message.error("获取班级列表失败:"+res.data.errorMsg);
            }
            this.examTypes = res.data;
          },

          handleSelect(selected) {
            this.addForm.studentName = selected.name
            this.addForm.studentId = selected.value+''
          },
          createStateFilter(queryString) {
            return (item) => {
              //item字段是全部所匹配到的大小写汉子
              return (
                  item.name.toLowerCase().indexOf(queryString.toLowerCase())>-1
              )
            }
          },

            /**
             * 关闭添加弹出框
             */
            closeDialog() {
                this.$refs.addFormRef.clearValidate();
                this.addForm.birth = "";
                this.addForm = {};
            },
            /**
             * 关闭编辑弹出框
             */
            editClose() {
                this.$refs.editFormRef.clearValidate();
                this.editForm = {};
            },

        },
        created() {
            this.getStudentScoreList();
            this.getExamType();
            // setTimeout(() => {
            //     this.loading = false;
            // }, 500);
        }
    };
</script>
